package com.account.web.controller.system;

import com.account.common.annotation.Log;
import com.account.common.core.controller.BaseController;
import com.account.common.core.domain.AjaxResult;
import com.account.common.core.domain.entity.SysRole;
import com.account.common.core.domain.entity.SysUser;
import com.account.common.core.page.TableDataInfo;
import com.account.common.enums.BusinessType;
import com.account.common.enums.ChannelUserType;
import com.account.common.utils.SecurityUtils;
import com.account.common.utils.StringUtils;
import com.account.common.utils.poi.ExcelUtil;
import com.account.system.service.ISysRoleService;
import com.account.system.service.ISysUserService;
import com.account.web.dto.system.ResetPasswordChannelUserDto;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 渠道管理员Controller
 *
 * @author a
 * @date 2025-07-05
 */
@RestController
@RequestMapping("/system/channel/agent")
public class ChannelAgentUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;


    /**
     * 查询渠道列表
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser sysUser) {
        sysUser.setAncestors(SecurityUtils.getUserId().toString());
        startPage();
        List<SysUser> list = userService.selectAgentUserList(sysUser);
        list.forEach(user -> {
            user.setPassword(StringUtils.EMPTY);
        });
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:channel:agent:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        String userId = SecurityUtils.getUserId().toString();
        user.setAncestors(userId);
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }


    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId)) {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }


    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        Long parentId = user.getParentId();
        SysUser parentSysUser = userService.selectUserById(parentId);
        if (parentSysUser == null) {
            return error("新增用户'" + user.getUserName() + "'失败，上级用户不存在");
        }
        user.setAncestors(parentSysUser.getAncestors() + parentId + ",");
        user.setNickName(user.getUserName());
        if (ChannelUserType.AGENT_1.getCode().equals(user.getUserType())) {
            user.setRoleIds(new Long[]{ChannelUserType.AGENT_1.getRoleId()});
        } else if (ChannelUserType.AGENT_2.getCode().equals(user.getUserType())) {
            user.setRoleIds(new Long[]{ChannelUserType.AGENT_2.getRoleId()});
        } else if (ChannelUserType.AGENT_3.getCode().equals(user.getUserType())) {
            user.setRoleIds(new Long[]{ChannelUserType.AGENT_3.getRoleId()});
        } else {
            return error("新增用户'" + user.getUserName() + "'失败，用户类型错误");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 重置渠道用户密码
     * @param dto
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:channel:agent:password')")
    @PostMapping("/reset/password")
    public AjaxResult resetPassword(@Validated @RequestBody ResetPasswordChannelUserDto dto) {
        return toAjax(userService.resetUserPwd(dto.getUserId(), SecurityUtils.encryptPassword(dto.getPassword())));
    }
}
